#include "writer.h"

#include <QDebug>
#include <QThread>

#include "utils.h"

template<>
size_t LibraryClient<'W'>::N = 0;

Writer::Writer(Library &library) :
    _library(library)
{
}

void Writer::runOnce()
{
    size_t maxIndex = _library.getBookCount();

    bool doWrite = maxIndex == 0 || (random(2) == 0 && !_library.isFull());

    if (doWrite) {
        qDebug() << "W" << _id << " writing new Book";

        sleep(_library.readInterval());
        int index = _library.addBook();

        qDebug() << "W" << _id << " added the Book #" << index;
    } else {
        size_t index = random(maxIndex);

        qDebug() << "W" << _id << " want to edit the Book #" << index;
        book_t book = _library.getBook(index);

        qDebug() << "W" << _id << " started editing the Book #" << index;
        sleep(_library.writeInterval());

        qDebug() << "W" << _id << " finished editing the Book #" << index;
        _library.returnBook(book);
    }
}
